<?php
session_start();
include('../includes/config.php');
include('../includes/functions.php');

// 检查用户是否已登录，且是医生角色
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'doctor') {
    header("Location: ../login.php");
    exit();
}

// 获取医生ID
$doctor_id = $_SESSION['user_id'];

// 获取医生信息
$stmt = $conn->prepare("SELECT * FROM users u JOIN doctors d ON u.id = d.user_id WHERE u.id = ?");
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$doctor_info = $stmt->get_result()->fetch_assoc();
$stmt->close();

// 获取今日预约数量
$today = date('Y-m-d');
$stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE doctor_id = ? AND appointment_date = ?");
$stmt->bind_param("is", $doctor_id, $today);
$stmt->execute();
$today_appointments = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// 获取本周预约数量
$week_start = date('Y-m-d', strtotime('monday this week'));
$week_end = date('Y-m-d', strtotime('sunday this week'));
$stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE doctor_id = ? AND appointment_date BETWEEN ? AND ?");
$stmt->bind_param("iss", $doctor_id, $week_start, $week_end);
$stmt->execute();
$week_appointments = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// 获取待处理预约
$stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE doctor_id = ? AND status = 'pending'");
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$pending_appointments = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// 获取最近病历数
$stmt = $conn->prepare("SELECT COUNT(*) as count FROM medical_records WHERE doctor_id = ?");
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$total_records = $stmt->get_result()->fetch_assoc()['count'];
$stmt->close();

// 获取最近5个预约
$stmt = $conn->prepare("SELECT a.*, p.name as patient_name, p.phone as patient_phone 
                       FROM appointments a 
                       JOIN patients p ON a.patient_id = p.id 
                       WHERE a.doctor_id = ? 
                       ORDER BY a.appointment_date DESC, a.appointment_time DESC 
                       LIMIT 5");
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$recent_appointments = $stmt->get_result();
$stmt->close();

// 获取最近5个病历
$stmt = $conn->prepare("SELECT mr.*, p.name as patient_name 
                       FROM medical_records mr 
                       JOIN patients p ON mr.patient_id = p.id 
                       WHERE mr.doctor_id = ? 
                       ORDER BY mr.created_at DESC 
                       LIMIT 5");
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$recent_records = $stmt->get_result();
$stmt->close();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>医生工作站 - 医院信息系统</title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
    <link rel="stylesheet" href="/assets\css/all_de197510.min.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <img src="../assets/images/hospital-logo.png" alt="医院标志" class="img-fluid rounded-circle mx-auto d-block" style="width: 80px;">
                        <h5 class="text-white mt-2"><?php echo htmlspecialchars($doctor_info['name']); ?></h5>
                        <p class="text-muted"><?php echo htmlspecialchars($doctor_info['department_name']); ?></p>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active text-white" href="index.php">
                                <i class="fas fa-home"></i> 工作台首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="appointments.php">
                                <i class="fas fa-calendar-check"></i> 预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="patients.php">
                                <i class="fas fa-user-injured"></i> 患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="records.php">
                                <i class="fas fa-notes-medical"></i> 病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="prescriptions.php">
                                <i class="fas fa-prescription"></i> 处方管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="schedule.php">
                                <i class="fas fa-clock"></i> 排班管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="profile.php">
                                <i class="fas fa-user-md"></i> 个人信息
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="../logout.php">
                                <i class="fas fa-sign-out-alt"></i> 退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">医生工作站</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="dropdown">
                            <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="fas fa-user-md"></i> <?php echo htmlspecialchars($_SESSION['user_name']); ?>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownMenuButton">
                                <li><a class="dropdown-item" href="profile.php">个人信息</a></li>
                                <li><a class="dropdown-item" href="../logout.php">退出登录</a></li>
                            </ul>
                        </div>
                    </div>
                </div>

                <!-- 统计卡片 -->
                <div class="row mb-4">
                    <div class="col-md-3 mb-3">
                        <div class="card text-white bg-primary">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="card-title">今日预约</h6>
                                        <h2 class="mb-0"><?php echo $today_appointments; ?></h2>
                                    </div>
                                    <i class="fas fa-calendar-day fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card text-white bg-success">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="card-title">本周预约</h6>
                                        <h2 class="mb-0"><?php echo $week_appointments; ?></h2>
                                    </div>
                                    <i class="fas fa-calendar-week fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card text-white bg-warning">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="card-title">待处理预约</h6>
                                        <h2 class="mb-0"><?php echo $pending_appointments; ?></h2>
                                    </div>
                                    <i class="fas fa-clock fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="card text-white bg-info">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="card-title">病历总数</h6>
                                        <h2 class="mb-0"><?php echo $total_records; ?></h2>
                                    </div>
                                    <i class="fas fa-notes-medical fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <!-- 最近预约 -->
                    <div class="col-md-6 mb-4">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">最近预约</h5>
                                <a href="appointments.php" class="btn btn-sm btn-primary">查看全部</a>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped table-hover">
                                        <thead>
                                            <tr>
                                                <th>患者</th>
                                                <th>日期时间</th>
                                                <th>状态</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($recent_appointments->num_rows > 0): ?>
                                                <?php while($appointment = $recent_appointments->fetch_assoc()): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($appointment['patient_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($appointment['appointment_date'] . ' ' . $appointment['appointment_time']); ?></td>
                                                        <td>
                                                            <?php 
                                                            switch($appointment['status']) {
                                                                case 'pending':
                                                                    echo '<span class="badge bg-warning">待确认</span>';
                                                                    break;
                                                                case 'confirmed':
                                                                    echo '<span class="badge bg-primary">已确认</span>';
                                                                    break;
                                                                case 'completed':
                                                                    echo '<span class="badge bg-success">已完成</span>';
                                                                    break;
                                                                case 'cancelled':
                                                                    echo '<span class="badge bg-danger">已取消</span>';
                                                                    break;
                                                                default:
                                                                    echo '<span class="badge bg-secondary">未知</span>';
                                                            }
                                                            ?>
                                                        </td>
                                                        <td>
                                                            <a href="appointment_details.php?id=<?php echo $appointment['id']; ?>" class="btn btn-sm btn-info">
                                                                <i class="fas fa-eye"></i>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="4" class="text-center">暂无预约记录</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 最近病历 -->
                    <div class="col-md-6 mb-4">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">最近病历</h5>
                                <a href="records.php" class="btn btn-sm btn-primary">查看全部</a>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped table-hover">
                                        <thead>
                                            <tr>
                                                <th>患者</th>
                                                <th>诊断</th>
                                                <th>日期</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($recent_records->num_rows > 0): ?>
                                                <?php while($record = $recent_records->fetch_assoc()): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($record['patient_name']); ?></td>
                                                        <td><?php echo htmlspecialchars(substr($record['diagnosis'], 0, 20) . (strlen($record['diagnosis']) > 20 ? '...' : '')); ?></td>
                                                        <td><?php echo htmlspecialchars(date('Y-m-d', strtotime($record['created_at']))); ?></td>
                                                        <td>
                                                            <a href="record_details.php?id=<?php echo $record['id']; ?>" class="btn btn-sm btn-info">
                                                                <i class="fas fa-eye"></i>
                                                            </a>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="4" class="text-center">暂无病历记录</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 日程表 -->
                <div class="row mb-4">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">本周工作日程</h5>
                                <a href="schedule.php" class="btn btn-sm btn-primary">管理排班</a>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <th>时间段</th>
                                                <?php
                                                $days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                                                $current_day = date('N'); // 1 (周一) 到 7 (周日)
                                                
                                                foreach($days as $index => $day) {
                                                    $day_num = $index + 1;
                                                    $class = ($day_num == $current_day) ? 'table-primary' : '';
                                                    echo '<th class="'.$class.'">'.$day.'</th>';
                                                }
                                                ?>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $time_slots = ['上午 (8:00-12:00)', '下午 (14:00-17:30)'];
                                            
                                            foreach($time_slots as $slot) {
                                                echo '<tr>';
                                                echo '<td>'.$slot.'</td>';
                                                
                                                for($i = 1; $i <= 7; $i++) {
                                                    $class = ($i == $current_day) ? 'table-primary' : '';
                                                    // 这里应该从数据库中获取排班信息，但为了简化起见，我们使用静态内容
                                                    $schedule_status = rand(0, 3);
                                                    $schedule_text = '';
                                                    
                                                    switch($schedule_status) {
                                                        case 0:
                                                            $schedule_text = '<span class="badge bg-success">门诊</span>';
                                                            break;
                                                        case 1:
                                                            $schedule_text = '<span class="badge bg-warning">专家门诊</span>';
                                                            break;
                                                        case 2:
                                                            $schedule_text = '<span class="badge bg-info">手术</span>';
                                                            break;
                                                        case 3:
                                                            $schedule_text = '<span class="badge bg-secondary">休息</span>';
                                                            break;
                                                    }
                                                    
                                                    echo '<td class="'.$class.'">'.$schedule_text.'</td>';
                                                }
                                                
                                                echo '</tr>';
                                            }
                                            ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 脚本 -->
    <script src="/assets\js/jquery-3.6.0.min.js"></script></script></script>
    <script src="/assets\js/bootstrap.bundle.min.js"></script></script></script>
    <script src="/assets\js/feather.min.js"></script></script></script>
    <script>
        // 初始化 feather 图标
        document.addEventListener('DOMContentLoaded', function() {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        });
    </script>
</body>
</html> 